package com.kcwx.web.controller.common;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import com.kcwx.common.constant.CacheConstants;
import com.kcwx.common.core.domain.R;
import com.kcwx.common.core.domain.entity.SysDictData;
import com.kcwx.common.core.redis.RedisCache;
import com.kcwx.common.utils.DictUtils;
import com.kcwx.common.utils.StringUtils;
import com.kcwx.common.utils.spring.SpringUtils;

@Api(tags = "通用接口-字典")
@RestController
@RequestMapping("/extra/dic")
@Slf4j
public class KcwsDicController {

    @ApiOperation(value = "读取全部字典信息")
    @PostMapping("/showalldic")
    public R<JSONObject> showalldic() {
        return R.ok(this.showall(true));
    }

    /**
     * 读取全部字典信息
     * @param withdic
     * @return JSONObject
     */
    private JSONObject showall(boolean withdic){
        JSONObject retv = new JSONObject();
        try{
            List<String> keys = new ArrayList<>(SpringUtils.getBean(RedisCache.class).keys(DictUtils.getCacheKey("*")));
            Collections.sort(keys);
            keys.forEach(p -> {
                JSONArray dataArray = new JSONArray();
                String key = p.replaceFirst(CacheConstants.SYS_DICT_KEY, "");
                if(withdic){
                    List<SysDictData> datalist = DictUtils.getDictCache(key);
                    if(StringUtils.isNotNull(datalist)) {
                        for (SysDictData sysDictData : datalist) {
                            JSONObject item = new JSONObject();
                            item.put("label", sysDictData.getDictLabel());
                            item.put("value", sysDictData.getDictValue());
                            item.put("cssClass", sysDictData.getCssClass());
                            item.put("listClass", sysDictData.getListClass());
                            dataArray.add(item);
                        }
                    }else{
                        log.error("{} 字典没有找到内容.", key);
                    }
                }
                retv.put(key, dataArray);
            });
        }catch(Exception e){
            retv.clear();
            retv.put("error", e.getLocalizedMessage());
        }
        return retv;
    }
}
